<template>
  <el-form :inline="true" :model="query" class="demo-form-inline">
    <el-form-item>
      <el-input v-model="query.userNameAccount" placeholder="请输入用户姓名/账号" clearable />
    </el-form-item>
    <el-form-item style="width: 200px;">
      <el-select v-model="query.userStatus" placeholder="请选择状态" clearable>
        <el-option label="请选择" :value="undefined" />
        <el-option label="启用" :value="true" />
        <el-option label="禁用" :value="false" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="GetUser">查询</el-button>
      <el-button @click="Reset">重置</el-button>
    </el-form-item>
  </el-form>

  <el-form-item>
    <el-button type="success" @click="OpenAdd">新增</el-button>
  </el-form-item>

  <el-table :data="users.items" border style="width: 100%;height: 500px;">
    <el-table-column type="index" label="序号" width="60px" />
    <el-table-column prop="userName" label="用户姓名" />
    <el-table-column prop="userNo" label="编号"/>
    <el-table-column prop="userAccount" label="用户账号" />
    <el-table-column prop="organizeName" label="所属组织" />
    <el-table-column prop="postName" label="岗位" />
    <el-table-column prop="userPhone" label="手机号" />
    <el-table-column prop="userEmail" label="邮箱" />
    <el-table-column prop="roleName" label="角色" />
    <el-table-column prop="userStatus" label="状态">
      <template #default="scope">
        <el-tag :type="scope.row.userStatus ? 'success' : 'info'">{{ scope.row.userStatus ? '启用' : '禁用' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="160">
      <template #default="scope">
        <el-button type="primary" link @click="OpenEdit(scope.row)">编辑</el-button>
        <el-button type="danger" link @click="DisableUser(scope.row)" v-if="scope.row.userStatus">禁用</el-button>
        <el-button type="success" link @click="EnableUser(scope.row)" v-else>启用</el-button>
        <el-button type="danger" link @click="DeleteUser(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    style="margin-top: 15px;"
    v-model:current-page="page.index"
    v-model:page-size="page.size"
    :page-sizes="[3,5,8,10]"
    :background="true"
    prev-text="上一页"
    next-text="下一页"
    layout="total, sizes, prev, pager, next, jumper"
    :total="page.total"
  />

  <el-dialog v-model="addDialogVisible" :title="dialogTitle" width="560px">
    <el-form ref="addFormRef" :model="addForm" label-width="112px">
      <el-form-item label="用户编号" prop="userNo">
        <el-input v-model="addForm.userNo" placeholder="请输入用户编号" :disabled="isEdit" />
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input v-model="addForm.userName" placeholder="请输入用户姓名" />
      </el-form-item>
      <el-form-item label="用户账号" prop="userAccount">
        <el-input v-model="addForm.userAccount" placeholder="请输入用户账号" />
      </el-form-item>
      <el-form-item label="登录密码" prop="userPassword" v-if="!isEdit">
        <el-input v-model="addForm.userPassword" type="password" placeholder="请输入登录密码" show-password />
      </el-form-item>
      <el-form-item label="性别" prop="userSex">
        <el-select v-model="addForm.userSex" placeholder="请选择性别" style="width: 100%">
          <el-option label="男" :value="true" />
          <el-option label="女" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="userPhone">
        <el-input v-model="addForm.userPhone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="邮箱" prop="userEmail">
        <el-input v-model="addForm.userEmail" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="所属组织" prop="organzationNo">
        <el-select v-model="addForm.organzationNo" placeholder="请选择所属组织" style="width: 100%">
          <el-option label="请选择" value="" />
          <el-option v-for="o in organizeOptions" :key="o.organizeNo" :label="o.organizeName" :value="o.organizeNo" />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="postNo">
        <el-select v-model="addForm.postNo" placeholder="请选择岗位" style="width: 100%">
          <el-option label="请选择" value="" />
          <el-option v-for="p in postOptions" :key="p.postNo" :label="p.postName" :value="p.postNo" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible=false">取消</el-button>
      <el-button type="primary" :loading="addSubmitting" @click="isEdit ? UpdateUser() : AddUser()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// @ts-ignore
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

const read = getReadClient(0)
const write = getWriteClient(0)

const users:any = reactive({ items: [] })
const page:any = reactive({ index: 1, size: 10, total: 0, totalPage: 0 })
const query:any = reactive({ userNameAccount: '', userStatus: undefined as undefined | boolean })

const addDialogVisible = ref(false)
const addSubmitting = ref(false)
const addFormRef = ref()
const isEdit = ref(false)
const dialogTitle = ref('新增用户')
const addForm:any = reactive({
  id: '',
  userNo: '',
  userAccount: '',
  userPassword: '',
  userName: '',
  userSex: true,
  userPhone: '',
  userEmail: '',
  organzationNo: '',
  postNo: ''
})

const organizeOptions:any = ref([])
const postOptions:any = ref([])

const GetUser = () => {
  read({
    url: 'sysread/api/User/GetUser',
    method: 'get',
    params: {
      UserNameAccount: query.userNameAccount,
      UserStatus: query.userStatus,
      Index: page.index,
      Size: page.size
    }
  }).then((res:any) => {
    users.items = res?.data?.data?.data || []
    page.total = res?.data?.data?.totalCount || 0
    page.totalPage = res?.data?.data?.totalPage || 0
  })
}

const Reset = () => {
  query.userNameAccount = ''
  query.userStatus = undefined
}

const OpenAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增用户'
  addForm.id = ''
  addForm.userNo = ''
  addForm.userAccount = ''
  addForm.userPassword = ''
  addForm.userName = ''
  addForm.userSex = true
  addForm.userPhone = ''
  addForm.userEmail = ''
  addForm.organzationNo = ''
  addForm.postNo = ''
  if(!organizeOptions.value?.length){ GetOrganizeOptions() }
  // 打开新增时，未选组织先清空岗位选项
  postOptions.value = []
  addDialogVisible.value = true
}

const OpenEdit = (row:any) => {
  isEdit.value = true
  dialogTitle.value = '编辑用户'
  addForm.id = row.id
  addForm.userNo = row.userNo || ''
  addForm.userAccount = row.userAccount || ''
  addForm.userPassword = row.userPassword||''
  addForm.userName = row.userName || ''
  addForm.userSex = !!row.userSex
  addForm.userPhone = row.userPhone || ''
  addForm.userEmail = row.userEmail || ''
  addForm.organzationNo = row.organzationNo || ''
  addForm.postNo = row.postNo|| ''
  if(!organizeOptions.value?.length){ GetOrganizeOptions() }
  if(addForm.organzationNo){ GetPostOptions(addForm.organzationNo) } else { postOptions.value = [] }
  addDialogVisible.value = true
}

const AddUser = () => {
  if(!addForm.userName){ return ElMessage.warning('请输入用户姓名') }
  if(!addForm.userAccount){ return ElMessage.warning('请输入用户账号') }
  if(!isEdit.value && !addForm.userPassword){ return ElMessage.warning('请输入登录密码') }
  addSubmitting.value = true
  write({
    url: 'syswrite/api/User/AddUser',
    method: 'post',
    data: {
      userNo: addForm.userNo,
      userAccount: addForm.userAccount,
      userPassword: addForm.userPassword,
      userName: addForm.userName,
      userSex: addForm.userSex,
      userPhone: addForm.userPhone,
      userEmail: addForm.userEmail,
      organzationNo: addForm.organzationNo,
      postNo: addForm.postNo
    }
  }).then((res) => {
    if(res.data.code==200){
      ElMessage.success('新增成功')
      addDialogVisible.value = false
      GetUser()
    }
    else{
      ElMessage.error(res.data.message)
    }
  }).finally(() => { addSubmitting.value = false })
}

const UpdateUser = () => {
  if(!addForm.userName){ return ElMessage.warning('请输入用户姓名') }
  if(!addForm.userAccount){ return ElMessage.warning('请输入用户账号') }
  addSubmitting.value = true
  write({
    url: 'syswrite/api/User/UpdateUser',
    method: 'post',
    data: addForm
  }).then((res) => {
    if(res.data.code==200){
      ElMessage.success('更新成功')
      addDialogVisible.value = false
      GetUser()
    }
    else{
      ElMessage.error(res.data.message)
    }
  }).finally(() => { addSubmitting.value = false })
}

// 启用用户
const EnableUser = (row:any) => {
  write({
    url: 'syswrite/api/User/EnableUser',
    method: 'post',
    params: { Id: row.id }
  }).then((res) => {
    if(res.data.code==200){
      ElMessage.success('启用成功')
      GetUser()
    }
    else{
      ElMessage.error(res.data.message)
    }
  })
}

// 禁用用户（通过UpdateUser设置userStatus为false）
const DisableUser = (row:any) => {
  write({
    url: 'syswrite/api/User/EnableUser',
    method: 'post',
    params:{
      id:row.id
    }
  }).then((res) => {
    if(res.data.code==200){
      ElMessage.success('禁用成功')
      GetUser()
    }
    else{
      ElMessage.error(res.data.message)
    }
  })
}

// 删除用户
const DeleteUser = (row:any) => {
  ElMessageBox.confirm(`确定删除用户"${row.userName}"吗？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    write({
      url: '/api/User/DeleteUser',
      method: 'post',
      params: { Id: row.id }
    }).then((res) => {
      if(res.data.code==200){
        ElMessage.success('删除成功')
        GetUser()
      }
      else{
        ElMessage.error(res.data.message)
      }
    })
  }).catch(() => {})
}

const GetOrganizeOptions = () => {
  read({ url: 'sysread/api/Organize/GetOrganize', method: 'get' })
  .then((res:any) => { organizeOptions.value = res?.data?.data || [] })
}

const GetPostOptions = (organizeNo:string) => {
  read({ url: '/api/Post/GetPost', method: 'get', params: { OrganizeNo: organizeNo, Index: 1, Size: 1000 } })
  .then((res:any) => { postOptions.value = res?.data?.data?.data || [] })
}

watch(page, () => { GetUser() }, { deep: true })

// 组织变更时，清空岗位并按组织过滤岗位列表
watch(() => addForm.organzationNo, (val:string) => {
  addForm.postNo = ''
  if(val){
    GetPostOptions(val)
  } else {
    postOptions.value = []
  }
})

onMounted(() => {
  GetUser()
})
</script>


